﻿using UnityEngine;
using UnityEngine.Rendering;
using XYRenderPipelines.Runtime;


namespace XYRendering.Vegetation
{

 public class VGInstancingRenderFeature : ScriptableRendererFeature
 {
        private class VGInstancingRenderPass : ScriptableRenderPass
        {
            private const string profilerTag = "Draw Instancing objects";
            
            private ProfilingSampler profilerSampler;
            public void Setup()
            {
                profilerSampler = new ProfilingSampler(profilerTag);
            }

            public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor)
            {
                VGInstancingDataRenererManager.GetInstance().OnPreExecute(cmd);
            }


            public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
            {
                CommandBuffer cmd = CommandBufferPool.Get(profilerTag);
                using (new ProfilingScope(cmd, profilerSampler))
                {
                    VGInstancingDataRenererManager.GetInstance().Execute(cmd);
                }
                context.ExecuteCommandBuffer(cmd);
                CommandBufferPool.Release(cmd);
            }


            public override void OnCameraCleanup(CommandBuffer cmd)
            {
                VGInstancingDataRenererManager.GetInstance().OnPostExecute(cmd);
            }
        }
        
        
        
        public static VGInstancingRenderFeature Instance { get; private set;}


        VGInstancingRenderPass _pass;
        
        
        public override void Create()
        {
            Instance = this;
            
            _pass = new VGInstancingRenderPass()
            {
                renderPassEvent = RenderPassEvent.AfterRenderingSkybox
            };
            _pass.Setup();
        }

        public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
        {
            if (renderingData.cameraData.cameraType == CameraType.Preview
                || renderingData.cameraData.cameraType == CameraType.Reflection
                || renderingData.cameraData.camera.gameObject.layer == LayerMask.NameToLayer("UI")
                || !VGInstancingDataRenererManager.GetInstance().isDeviceSupported)
                return;

            
            if (!VGInstancingDataRenererManager.GetInstance().PrepareForExecute())
                return;
                
            renderer.EnqueuePass(_pass);
        }
        
    }
}